package com.universe.titan.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @Author : linmaobo
 * @create 2022/12/8
 * 消息处理器
 */
@Component
@Slf4j
public class MessageHandle {

    /**
     * 根据指定客户端session发送给消息
     * @param socketServer  客户端session
     * @param message 发送消息内容
     * @throws IOException
     */
    public void  sendToOneUserBySession(WebSocketServer socketServer, MessageInfo message) throws IOException {
        // 空消息不消费
        if (StringUtils.isEmpty(message.getData())){
            return;
        }
        socketServer.getSession().getBasicRemote().sendText(message.getData().toString());
    }

    /**
     * 给指定的用户身份标识发送消息
     * @param message 发送消息内容
     * @throws IOException
     */
    public void  sendToOneUser(MessageInfo message) throws IOException {
        try {
            //根据token获取连接的客户端
            WebSocketServer socketServer = WebSocketServer.clients.get(message.getReceiveUserIdentity());
            //向客户端发送信息
            sendToOneUserBySession(socketServer, message);
        }catch (Exception e){
            log.info("send to one  user found  error : {}", e.getStackTrace());
            sendToOneUserRetrySend();
        }
    }



    /**
     * 重试机制： 未设计
     * TODO 重试机制
     */
    public void  sendToOneUserRetrySend(){

    }


    /**
     * 广播消息
     * @throws IOException
     */
    public void  broadcast(MessageInfo message) throws IOException {
        try {
            // 广播发送给所有用户
            Set<Map.Entry<String, WebSocketServer>> entries = WebSocketServer.clients.entrySet();
            for (Map.Entry<String, WebSocketServer> entry : entries) {
                WebSocketServer webSocketServer = entry.getValue();
                sendToOneUserBySession(webSocketServer, message);
            }
        }catch (Exception e){
            log.info("send to broadcast found  error : {}", e.getStackTrace());

        }

    }





}
